package com.example.mplayer.screens

import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.mplayer.data.CardKey
import com.example.mplayer.viewmodels.CardKeyViewModel
import com.example.mplayer.viewmodels.CourseLoadingState

@Composable
fun CardManagementScreen(
    modifier: Modifier = Modifier,
    onBackClick: () -> Unit,
    backIcon: @Composable () -> Unit,
    viewModel: CardKeyViewModel = viewModel()
) {
    var showAddDialog by remember { mutableStateOf(false) }
    var editingCardKey by remember { mutableStateOf<CardKey?>(null) }
    
    val cardKeys by viewModel.allCardKeys.collectAsState(initial = emptyList())
    val courseLoadingState by viewModel.courseLoadingState.collectAsState()
    val context = LocalContext.current

    Column(
        modifier = modifier.fillMaxSize()
    ) {
        // 顶部栏
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .clickable(onClick = onBackClick)
                .padding(16.dp),
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            backIcon()
            Text(text = "返回")
        }

        // 内容区域
        Box(modifier = Modifier.fillMaxSize()) {
            LazyColumn(
                modifier = Modifier.fillMaxSize(),
                contentPadding = PaddingValues(16.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                items(cardKeys) { cardKey ->
                    CardKeyItem(
                        cardKey = cardKey,
                        onEdit = { editingCardKey = it },
                        onDelete = { viewModel.deleteCardKey(it) }
                    )
                }
            }

            // 添加按钮
            FloatingActionButton(
                onClick = { showAddDialog = true },
                modifier = Modifier
                    .align(Alignment.BottomEnd)
                    .padding(16.dp)
            ) {
                Icon(Icons.Default.Add, contentDescription = "添加卡密")
            }

            // Show loading state
            when (courseLoadingState) {
                is CourseLoadingState.Loading -> {
                    CircularProgressIndicator(
                        modifier = Modifier.align(Alignment.Center)
                    )
                }
                is CourseLoadingState.Error -> {
                    val error = (courseLoadingState as CourseLoadingState.Error).message
                    LaunchedEffect(error) {
                        Toast.makeText(context, error, Toast.LENGTH_SHORT).show()
                    }
                }
                is CourseLoadingState.Success -> {
                    LaunchedEffect(courseLoadingState) {
                        Toast.makeText(context, "课程获取成功", Toast.LENGTH_SHORT).show()
                    }
                }
                else -> { /* Initial state, do nothing */ }
            }
        }
    }

    // 添加/编辑对话框
    if (showAddDialog || editingCardKey != null) {
        CardKeyDialog(
            cardKey = editingCardKey,
            onDismiss = {
                showAddDialog = false
                editingCardKey = null
            },
            onConfirm = { key, note ->
                if (editingCardKey != null) {
                    viewModel.updateCardKey(editingCardKey!!.copy(key = key, note = note))
                } else {
                    viewModel.addCardKey(key, note)
                }
                showAddDialog = false
                editingCardKey = null
            }
        )
    }
}

@Composable
private fun CardKeyItem(
    cardKey: CardKey,
    onEdit: (CardKey) -> Unit,
    onDelete: (CardKey) -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(modifier = Modifier.weight(1f)) {
                Text(text = cardKey.key, style = MaterialTheme.typography.bodyLarge)
                if (cardKey.note.isNotEmpty()) {
                    Text(
                        text = cardKey.note,
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
            Row {
                IconButton(onClick = { onEdit(cardKey) }) {
                    Icon(Icons.Default.Edit, contentDescription = "编辑")
                }
                IconButton(onClick = { onDelete(cardKey) }) {
                    Icon(Icons.Default.Delete, contentDescription = "删除")
                }
            }
        }
    }
}

@Composable
private fun CardKeyDialog(
    cardKey: CardKey?,
    onDismiss: () -> Unit,
    onConfirm: (key: String, note: String) -> Unit
) {
    var key by remember { mutableStateOf(cardKey?.key ?: "") }
    var note by remember { mutableStateOf(cardKey?.note ?: "") }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(text = if (cardKey == null) "添加卡密" else "编辑卡密") },
        text = {
            Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                OutlinedTextField(
                    value = key,
                    onValueChange = { key = it },
                    label = { Text("卡密") }
                )
                OutlinedTextField(
                    value = note,
                    onValueChange = { note = it },
                    label = { Text("备注") }
                )
            }
        },
        confirmButton = {
            TextButton(
                onClick = { onConfirm(key, note) },
                enabled = key.isNotBlank()
            ) {
                Text("确定")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}